﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;
using System.Reflection;
using Journal.Domain;
using NHibernate.Criterion;

namespace Journal.Persistence
{

    public class CalendarPersistenceManager : ICalendarPersistenceManager
    {

        public void Add(Calendar calendar)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Save(calendar);
                transaction.Commit();
            }
        }

        public void Update(Calendar calendar)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Update(calendar);
                transaction.Commit();
            }
        }

        public void Delete(Calendar calendar)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            using (ITransaction transaction = session.BeginTransaction())
            {
                session.Delete(calendar);
                transaction.Commit();
            }
        }

        public Calendar GetById(Guid calendarId)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                return session.Get<Calendar>(calendarId);
            }
        }

        public Calendar GetByName(string name)
        {
            using (ISession session = NHibernateHelper.OpenSession())
            {
                Calendar calendar = session
                    .CreateCriteria(typeof(Calendar))
                    .Add(Restrictions.Eq("Name", name))
                    .UniqueResult<Calendar>();
                return calendar;
            }
        }
    }

}
